import React, { useState, useEffect, useRef } from 'react'
import axios from '../../axios'
import { SystemQRcodeOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import styles from './My.module.css'
import sao from '../../assets/扫一扫.png'
import yang from '../../assets/金币商城.png'
import wo from '../../assets/我的.png'
import Ai from '../../assets/智能Ai.png'
import { Empty, Image, InfiniteScroll, List, DotLoading, Toast, Button } from 'antd-mobile'
import Ip from '../../components/map/Ip'

interface UserData {
  img?: string;
  userName?: string;
  money?: number;
  // Add other properties from your API response here if needed
}

interface DynamicItem {
  _id: string;
  title: string;
  time: string;
  img: string;
  media_type?: string;
  address?: string;
  comment: any[];
  like: any[];
  user_id: {
    userName: string;
    img: string;
  };
  __v?: number;
}

export default function My() {
  const navigate = useNavigate()
  const [list, setList] = useState<UserData>({})
  const [dynamics, setDynamics] = useState<DynamicItem[]>([])
  const [loadingDynamics, setLoadingDynamics] = useState(false)
  const id = localStorage.getItem('user')
  
  const getData = () => {
    axios.get('/index?id=' + id).then(res => {
      setList(res.data.data)
    })
  }
  
  const getUserDynamics = async () => {
    if (!id) return;
    
    try {
      setLoadingDynamics(true);
      const res = await axios.get(`/getUserDynamics?userId=${id}`);
      if (res.data.code === 200 && res.data.data) {
        setDynamics(res.data.data);
      }
      setLoadingDynamics(false);
    } catch (error) {
      console.error('获取用户动态失败', error);
      setLoadingDynamics(false);
    }
  }
  
  useEffect(() => {
    getData();
    getUserDynamics();
  }, [])

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }

  // 处理媒体错误
  const handleMediaError = (e: React.SyntheticEvent<HTMLVideoElement, Event>, item: DynamicItem) => {
    console.error('视频加载失败', e, item);
    Toast.show({
      content: '视频加载失败，请稍后再试',
      position: 'bottom',
    });
  };

  // 检查URL是否有效
  const checkVideoUrl = (url: string): string => {
    try {
      const baseURL = axios.defaults.baseURL || 'http://localhost:3000';
      
      // 处理服务器返回的格式化地址
      if (url.startsWith('/upload/')) {
        return `${baseURL}${url}`;
      }
      
      // 如果是带有http的完整路径，直接返回
      if (url.startsWith('http')) {
        return url;
      }
      
      // 如果包含.mp4等格式，可能是服务器路径
      if (url.includes('.mp4') || url.includes('.webm') || url.includes('.mov')) {
        if (url.startsWith('/')) {
          return `${baseURL}${url}`;
        } else {
          return `${baseURL}/upload/${url}`;
        }
      }
      
      // 其他情况，尝试处理为完整路径
      return url;
    } catch (error) {
      console.error('URL处理失败', url, error);
      return url;
    }
  };

  // 根据文件路径获取视频类型
  const getVideoType = (path: string) => {
    if (path.endsWith('.mp4')) return 'video/mp4';
    if (path.endsWith('.webm')) return 'video/webm';
    if (path.endsWith('.mov')) return 'video/quicktime';
    return 'video/mp4'; // 默认类型
  };
  
  // 渲染媒体内容
  const renderMedia = (item: DynamicItem) => {
    if (!item.img) {
      return <div className={styles.noMedia}>暂无媒体内容</div>;
    }
    
    // 记录原始URL，便于调试
    console.log('Media URL:', item.img, 'Type:', item.media_type);
    
    if (item.media_type === 'video') {
      // 处理视频URL
      const videoUrl = checkVideoUrl(item.img);
      console.log('处理后的视频URL:', videoUrl);
      const videoType = getVideoType(item.img);
      
      return (
        <div className={styles.dynamicVideo}>
          <div className={styles.videoWrapper}>
            <video 
              key={videoUrl} // 强制重新加载视频元素
              className={styles.videoContent}
              controls
              preload="metadata"
              playsInline
              controlsList="nodownload" 
              onError={(e) => handleMediaError(e, item)}
            >
              <source src={videoUrl} type={videoType} />
              您的浏览器不支持 HTML5 视频播放
            </video>
          </div>
          <div className={styles.videoInfo}>
            <div className={styles.videoMeta}>
              <span>{item.title || '视频内容'}</span>
              <Button 
                size='mini' 
                onClick={(e) => {
                  e.stopPropagation();
                  window.open(videoUrl, '_blank');
                }}
              >
                外部播放
              </Button>
            </div>
          </div>
        </div>
      );
    } else {
      // 图片处理
      return (
        <div className={styles.dynamicImages}>
          <Image
            src={item.img}
            className={styles.dynamicImage}
            fit="cover"
            lazy
            fallback={<div className={styles.imagePlaceholder}>图片加载失败</div>}
          />
        </div>
      );
    }
  }

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.avatarContainer}>
          <img 
            src={list.img} 
            alt="用户头像" 
            className={styles.avatar}
          />
        </div>
        
        <div className={styles.userInfo}>
          <h2 className={styles.username}>{list.userName || '用户名'}</h2>
          <Ip />
        </div>
        
        <div className={styles.qrButton} onClick={() => navigate('/er')}>
          <SystemQRcodeOutline fontSize={24} />
        </div>
      </div>
     
      <div className={styles.gong}>
        <div className={styles.title}><b>功能操作</b></div>
        <div className={styles.functionGrid}>
          <div 
            className={styles.functionItem} 
            onClick={() => navigate('/sao')}
          >
            <img src={sao} alt="扫一扫" className={styles.functionIcon} />
            <span className={styles.functionText}>扫一扫</span>
          </div>
          
          <div 
            className={styles.functionItem} 
            onClick={() => navigate('/deposit')}
          >
            <img src={yang} alt="洋币" className={styles.functionIcon} />
            <span className={styles.functionText}>洋币</span>
          </div>
          
          <div className={styles.functionItem}>
            <img src={Ai} alt="Ai" className={styles.functionIcon} />
            <span className={styles.functionText} onClick={()=>{
              navigate('/bot')
            }}>不能说的秘密</span>
          </div>
          
          <div 
            className={styles.functionItem} 
            onClick={() => navigate('/xiu')}
          > 
            <img src={wo} alt="我的信息" className={styles.functionIcon} />
            <span className={styles.functionText}>我的信息</span>
          </div>
        </div>
      </div>
      
      {/* 用户动态区域 */}
      <div className={styles.dynamicsSection}>
        <div className={styles.title}><b>我的动态</b></div>
        
        {loadingDynamics ? (
          <div className={styles.loadingContainer}>
            <DotLoading color='primary' />
            <span>加载中...</span>
          </div>
        ) : dynamics.length > 0 ? (
          <List>
            {dynamics.map(item => (
              <List.Item
                key={item._id}
                className={styles.dynamicItem}
                onClick={() => navigate(`/square/detail?id=${item._id}`)}
              >
                <div className={styles.dynamicContent}>
                  <div className={styles.dynamicTitle}>{item.title}</div>
                  
                  {renderMedia(item)}
                  
                  <div className={styles.dynamicFooter}>
                    <span className={styles.dynamicTime}>{formatDate(item.time)}</span>
                    {item.address && (
                      <span className={styles.dynamicLocation}>{item.address}</span>
                    )}
                    <div className={styles.dynamicStats}>
                      <span>👍 {item.like?.length || 0}</span>
                      <span>💬 {item.comment?.length || 0}</span>
                    </div>
                  </div>
                </div>
              </List.Item>
            ))}
          </List>
        ) : (
          <Empty
            description="暂无动态内容"
            imageStyle={{ width: 128 }}
          />
        )}
      </div>
    </div>
  )
}